﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using Efm.Progress;

namespace Test
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {


        static public void DoEvents()
        {
            var frame = new DispatcherFrame();
            Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
                new DispatcherOperationCallback(ExitFrame), frame);
            Dispatcher.PushFrame(frame);
        }

        static public object ExitFrame(object f)
        {
            ((DispatcherFrame)f).Continue = false;

            return null;
        }

        private ProgressBox _progressBox;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            int count;
            int.TryParse(CountTextBox.Text, out count);
            _progressBox = new ProgressBox(count)
            {
                Title = TitleTextBox.Text,
                Text = ContentTextBox.Text,
                ShowWindow = ShowWindow.IsChecked != null && ShowWindow.IsChecked.Value,
                ShowCancelButton = ShowCancelButton.IsChecked != null && ShowCancelButton.IsChecked.Value,
                ShowPauseButton = ShowPauseButton.IsChecked != null && ShowPauseButton.IsChecked.Value,
            };

            _progressBox.Work += box_Work;

            _progressBox.Report += box_Report;
            _progressBox.Start();

        }

        void box_Report(object sender, ReportEventArgs e)
        {
            if (_progressBox != null) _progressBox[0].Value = e.Value[0];
        }

        void box_Work(object sender, EventArgs e)
        {
            Progress(_progressBox.Count - 1);
        }


        private void Progress(object obj)
        {
            var setIndex = obj is int ? (int)obj : 0;
            var rand = new Random().Next(200);
            for (var i = 0; i < rand; )
            {
                Thread.Sleep(1);
                DoEvents();
                if (_progressBox.IsCancelled) break;
                if (_progressBox.IsPaused) continue;

                for (var u = 0; u < setIndex; u++) Progress(u);

                _progressBox[setIndex].Value = (double)i++ * 100 / rand;
            }


        }


    }
}
